package com.aaa.mrcai.service.impl;

import com.aaa.mrcai.mapper.GoodsCategoryMapper;
import com.aaa.mrcai.pojo.entity.GoodsCategory;
import com.aaa.mrcai.pojo.vo.GoodsCategoryVo;
import com.aaa.mrcai.query.GoodsCategoryQuery;
import com.aaa.mrcai.result.AjaxResult;
import com.aaa.mrcai.service.GoodsCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Demo class
 *
 * @Author: Wang
 * @Date: Created in 20:25 2021/12/6
 */
@Service
public class GoodsCategoryServiceImpl implements GoodsCategoryService {

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;


    @Autowired
    private HttpSession session;

    @Override
    public AjaxResult list(GoodsCategoryQuery query) {

        List<GoodsCategory> goodsCategoryList = goodsCategoryMapper.queryGoodsCategory(query);
        Long totalCount = goodsCategoryMapper.queryGoodsCategoryTotalCount(query);
        Map<String, Object> map = new HashMap<>();

        map.put("currentPageData", goodsCategoryList);
        map.put("currentDataTotal", totalCount);
        return AjaxResult.success(map);
    }



    @Override
    public AjaxResult addGoodsCategory(GoodsCategoryVo goodsCategoryVo) {
        Long count = goodsCategoryMapper.isGoodsCategoryExists(goodsCategoryVo.getCategory());
        if (count > 0) {
            return AjaxResult.defeated("对不起，商品类别已存在");
        }
        int i = goodsCategoryMapper.addGoodsCategory(goodsCategoryVo);

        if (i > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.defeated();
    }

    @Override
    public AjaxResult getGoodsCategory(int id) {
        GoodsCategoryVo r = goodsCategoryMapper.getGoodsCategory(id);
        session.setAttribute("currentUpdateGoodsCategory",r);
        return AjaxResult.success(r);
    }

    @Override
    public AjaxResult updateGoodsCategory(GoodsCategoryVo goodsCategoryVo) {
        GoodsCategoryVo currentUpdateGoodsCategory = (GoodsCategoryVo) session.getAttribute("currentUpdateGoodsCategory");

       if (!goodsCategoryVo.getId().equals(currentUpdateGoodsCategory.getId())){
          return AjaxResult.defeated("不可以乱改哦");

        }
        long count = goodsCategoryMapper.isUpdateGoodsCategoryExists(goodsCategoryVo);

        if (count > 0) {
            return AjaxResult.defeated("已存在该商品类别");
        }

        int i = goodsCategoryMapper.updateGoodsCategory(goodsCategoryVo);

        if (i > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.defeated();
    }

    @Override
    public AjaxResult deleteGoodsCategory(int id) {
        int  r = goodsCategoryMapper.deleteGoodsCategory(id);
        session.setAttribute("currentUpdateGoodsCategory",r);
        return AjaxResult.success(r);
    }


}
